import './shared/assets/main.css'

import { createApp } from 'vue'
import { createPinia } from 'pinia'

import App from './App.vue'
import router from './router'
import type { RouteRecordRaw } from 'vue-router';
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import { loadModules, normalizeRoutePath} from './platform/moduleLoader';
import { CommandService } from './platform/service/CommandService';
import type { ICommandService } from './core/commands/command.type';

const app = createApp(App);

app.provide<ICommandService>('commandService', new CommandService());

loadModules()
  .then(modules => {
    // 获取父路由的记录
    const parentRoute = router.getRoutes().find(r => r.name === 'editor');
    if (!parentRoute) {
      console.error('找不到名为 "editor" 的父路由');
      return;
    }
    // 1. 注册模块路由
    modules.forEach(module => {
      const routes = module.registerRoutes();
      if (Array.isArray(routes)) {
        routes.forEach(route => {
          console.log('添加子路由', route);
      
          // 创建新的子路由记录
          const childRoute: RouteRecordRaw = {
            ...route,
            // 确保路径是相对于父路由的
            path: route.path.replace(/^\//, '') // 移除前导斜杠
          };
          
          // 添加到父路由的 children 中
          parentRoute.children = parentRoute.children || [];
          parentRoute.children.push(childRoute);
          
          // 使用 Vue Router 的 addRoute 方法添加子路由
          router.addRoute(parentRoute.name as string, childRoute);
        });
      }
    });

    // 2. 使用路由器并挂载应用
    app.use(router);
    app.use(ElementPlus);
    app.use(createPinia());

    // 3. 执行模块挂载钩子
    modules.forEach(module => module.onMount?.());

    app.mount('#app');
    
    // 4. 调试输出
    console.debug('已注册的路由:', router.getRoutes());
  })
  .catch(error => {
    console.error('模块加载失败:', error);
    // 错误回退机制
    const fallbackElement = document.createElement('div');
    fallbackElement.innerHTML = '<h2>应用加载失败</h2><p>请检查控制台获取更多信息</p>';
    document.body.appendChild(fallbackElement);
  });

// 应用卸载时清理模块
window.addEventListener('beforeunload', () => {
  if (window.modules) {
    (window.modules as any[]).forEach(module => module.onUnmount?.());
  }
});